package hbt.dao;

import hbt.util.HibernateUtil;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import entities.Alumno;
@SuppressWarnings("unchecked")
public class HibernateAlumnoDAO {
	private static SessionFactory sf;
	private static HibernateAlumnoDAO instancia;
	
	public static HibernateAlumnoDAO getInstancia(){
		if(instancia == null)
			instancia = new HibernateAlumnoDAO();
		if(sf == null)
			sf = HibernateUtil.getSessionFactory();
		return instancia;
	}
	
	public boolean grabarAlumno(Alumno alumno){
		try {
			Session session = sf.openSession();
			session.beginTransaction();
			session.persist(alumno);
			session.getTransaction().commit();
			session.flush();
			session.close();
			return true;
		} catch (HibernateException e) {
			return false;
		}
	}
	
	public List<Alumno> getAlumnos(){
		Session session = sf.openSession();
		Query query = session.createQuery("from Alumno");
		List<Alumno> alumnos = query.list();
		return alumnos;
	}

	public List<Alumno> buscarAlumno(String numeroDoc, String nombre) {
		Session session = sf.openSession();
		String querySTR = "from Alumno a where 1 = 1";
		if(numeroDoc != null && !"".equalsIgnoreCase(numeroDoc)){
			querySTR += " AND a.personaId.numero = :numeroDoc";
		}
		if(nombre != null && !"".equalsIgnoreCase(nombre)){
			nombre = "%" + nombre + "%";
			querySTR += " AND a.nombre LIKE :nombre";
		}
		
		Query query = session.createQuery(querySTR);
		
		if(numeroDoc != null && !"".equalsIgnoreCase(numeroDoc)){
			query.setParameter("numeroDoc", numeroDoc);
		}
		if(nombre != null && !"".equalsIgnoreCase(nombre)){
			query.setParameter("nombre", nombre);
		}
		List<Alumno> alumnos = (List<Alumno>)query.list();
		return alumnos;
	}
	

}
